<?php

class Maillist_Model_SubscribersMapper{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable(){
        if (null === $this->_dbTable)
            $this->setDbTable('Maillist_Model_DbTable_Subscribers');
        return $this->_dbTable;
    }
	
	public function fetchAll($query=null,$start=-1,$limit=-1){
		$t = $this->getDbTable();
        $s = $t->select();
        if ((-1!=$start) && (-1!=$limit)){
            $s->limit($limit,$start); }
        if (null!=$query) $s->where(new Zend_Db_Expr("Name1 LIKE '%".$query."%'") );
		return $t->fetchAll( $s)->toArray();
	}
    /*
     * Возвращает подписчиков, которые не получили самую свежую рассылку
     */
    public function fetchSubscribers4Sending($postId,$start=null,$limit=null){
        $t1 = $this->getDbTable();
        //$t2 = new Maillist_Model_DbTable_Posts();
        $s = $t1->select()->setIntegrityCheck(false)
                //->from(array('t1'=>$t1->info(Zend_Db_Table_Abstract::NAME)))
                ->where('(PostId IS NULL) OR (PostId < '.$postId.')');
        if ((null!=$start) && (null!=$limit))
            $s->limit($limit,$start);
        $set = $t1->fetchAll($s);        
        $result=array();
        foreach($set as $row){
            $r = $row->toArray();
            $result[] = new Maillist_Model_Subscriber($r);
        }
        
        return $result;
	}
    
    public function count(){
        $t = $this->getDbTable();
        $a=$t->fetchRow($t->select()->from($t,new Zend_Db_Expr("COUNT(Id) as C")))->toArray();
        return $a['C'];
    }
    
    public function save($params){
        $t = $this->getDbTable();
        if (isset($params['Id']))
            $t->update($params,array('Id=?'=>$params['Id']));
        else
            return $t->insert($params);
        return $params['Id'];
    }
    
    public function delete($id){
        $this->getDbTable()->delete(array('Id=?'=>$id));
    }
}
?>